package cn.tedu.gxtt.passport.security;

import cn.tedu.gxtt.commons.ex.ServiceException;
import cn.tedu.gxtt.commons.pojo.user.dto.UserLoginDTO;
import cn.tedu.gxtt.commons.restful.ResponseCode;
import cn.tedu.gxtt.passport.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.trace("根据用户名查询尝试登录的用户信息，用户名:{}" , s);
        UserLoginDTO user = userMapper.getLoginInfoByUsername(s);
        log.trace("根据用户名查询的结果:{}",user);
        if (user == null){
            log.trace("没有查询到用户信息,即将抛出异常");
            throw new ServiceException(ResponseCode.ERR_CATEGORY_NOT_FOUND,"用户名不存在");
        }
        log.info("查询到匹配的管理员数据，需要将此数据转换为UserDetails并返回");
        UserDetails userDetails = User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .accountExpired(false)
                .accountLocked(false)
                .disabled(false)
                .credentialsExpired(false)
                .authorities(new String[] {})
                .build();
        return userDetails;
    }
}
